﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Server.ActivityFeed;
using ESF.SharePoint.Utility;
using ESF.SharePoint.Entities;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Portal.WebControls;
using System.Globalization;

namespace ESF.SharePoint.Formatters
{
    class ProfileChangePropertyFormatter : ActivityFormatter
    {

        public override ActivityEvent Format(ActivityEvent activity, object parameters)
        {
            return null;
        }

        public override CustomActivityEvent Format(CustomActivityEvent activity, object parameters)
        {
            List<Entity> usersWithUpdatedProfile = (List<Entity>)parameters;

            if (usersWithUpdatedProfile != null)
            {
                ActivityTemplateVariable atv = activity.ATV;
                atv.List = new List();
                int userProfileCount = usersWithUpdatedProfile.Count;
                if (userProfileCount == 1)
                {
                    atv.Name = string.Empty;
                }
                if (userProfileCount > 1)
                {
                    if (userProfileCount == 2)
                        atv.Name = string.Format("also another user has profile changes", usersWithUpdatedProfile.Count);
                    else
                        atv.Name = string.Format("There are {0} users with profile changes", userProfileCount - 1);

                    StringBuilder accounts = new StringBuilder();
                    foreach (var entity in usersWithUpdatedProfile)
                    {
                        if (string.Compare(activity.Publisher.AccountName, entity.AccountName, true) != 0)
                        {
                            string picture = entity.Picture;
                            picture = ESF.SharePoint.Utility.ESFUtility.GetUserPicture(picture);
                            string userHtml = string.Format("<a href=\"{0}\" alt=\"{2}\"><img src=\"{1}\" alt=\"{2}\" /></a> ",
                                SPHttpUtility.HtmlUrlAttributeEncode(SPHttpUtility.UrlPathEncode(entity.Href, false)),
                                SPHttpUtility.HtmlUrlAttributeEncode(SPHttpUtility.NoEncode(picture)),
                                entity.Name);
                            accounts.Append(userHtml);
                        }
                    }
                    atv.Value = accounts.ToString();

                    activity.Modified = true;
                }
            }

            return activity;
        }

    }
}
